package com.itheima.utils;

import com.itheima.domain.system.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自动登录功能
 * 2021/10/16 15:53
 * create by guowenliang
 */
@WebFilter(value = "/login.jsp")
public class AutoLoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 会话域有存username，则自动登录(就是浏览器登陆过，只要浏览器不关，都会自动跳转)
        if (request.getSession().getAttribute("username") != null) {
            User user = (User)request.getSession().getAttribute("user");
            request.setAttribute("user",user);
            request.getRequestDispatcher(request.getContextPath()+"/WEB-INF/pages/home/main.jsp").forward(request,response);
        } else {
            Cookie[] cookies = request.getCookies();
            String autoLogin = null;
            String username = null;
            String password = null;

            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("autoLogin")){
                    autoLogin = cookie.getValue();
                }
                if (cookie.getName().equals("username")){
                    username = cookie.getValue();
                }
                if (cookie.getName().equals("password")){
                    password = cookie.getValue();
                }
            }
            // 有勾选自动登录，下次自动登录
            if ("yes".equals(autoLogin)){
//                System.out.println("通过cookie自动登录");
                request.getRequestDispatcher(request.getContextPath()+"/loginServlet?method=login&username="+username+"&password="+password+"&remember=yes&autoLogin=yes").forward(request,response);
            }else {
                chain.doFilter(request, response);
            }
        }
    }
}
